package com.caihao.activemqdemo.producer;

import com.caihao.activemqdemo.entity.Student;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Queue;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * create by caihao on 2020/8/31
 */
@RestController
@Slf4j
public class ProducerController {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    @Qualifier("queue")
    private Queue queue;

    @Autowired
    @Qualifier("delayQueue")
    private Queue delayQueue;

    /**
     * 发送普通消息队列
     */
    @GetMapping("/queue")
    public String sendQueue() throws JsonProcessingException {
        Student student = new Student(1, "张三", new Date());
        ObjectMapper objectMapper = new ObjectMapper();
        String msg = objectMapper.writeValueAsString(student);
        log.info("发送-开始");
        jmsMessagingTemplate.convertAndSend(queue, msg);
        log.info("发送-结束");
        return "send queue success";
    }

    /**
     * 发送延迟消息队列
     */
    @GetMapping("/delay-queue")
    public String sendDelayQueue() throws JsonProcessingException {
        Student student = new Student(2, "李四", new Date());
        ObjectMapper objectMapper = new ObjectMapper();
        String msg = objectMapper.writeValueAsString(student);
        Map<String, Object> headers = new HashMap<>();
        // 延迟5秒
        headers.put(ScheduledMessage.AMQ_SCHEDULED_DELAY, 5000);
        log.info("延迟发送-开始");
        jmsMessagingTemplate.convertAndSend(delayQueue, msg, headers);
        log.info("延迟发送-结束");
        return "send delay queue success";
    }

}
